package org.jeecg.modules.message.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.system.base.service.impl.JeecgServiceImpl;
import org.jeecg.modules.app.userSetting.entity.AppUserSetting;
import org.jeecg.modules.app.userSetting.service.AppUserSettingService;
import org.jeecg.modules.message.entity.SysMessage;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.jeecg.modules.message.handle.enums.SendMsgStatusEnum;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.jeecg.modules.message.mapper.SysMessageTemplateMapper;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.message.util.TemplateUtil;
import org.jeecg.modules.system.entity.SysFiles;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysFilesService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 消息模板
 * @Author: jeecg-boot
 * @Date: 2019-04-09
 * @Version: V1.0
 */
@Service
public class SysMessageTemplateServiceImpl extends JeecgServiceImpl<SysMessageTemplateMapper, SysMessageTemplate> implements ISysMessageTemplateService {

    @Resource
    private ISysFilesService filesService;
    @Resource
    private ISysMessageService messageService;
    @Resource
    private ISysUserService userService;
    @Resource
    private AppUserSettingService userSettingService;
    @Resource
    private SysMessageTemplateMapper sysMessageTemplateMapper;


    @Override
    public List<SysMessageTemplate> selectByCode(String code) {
        return sysMessageTemplateMapper.selectByCode(code);
    }

    @Override
    public boolean sendEmailSms(String email, JSONObject params, String model) {
        boolean result = false;

        List<SysMessageTemplate> templates = this.selectByCode(model);

        SysMessageTemplate template = new SysMessageTemplate();

        if (templates != null && templates.size() > 0) {
            template = templates.get(0);

            if (model != null && !model.isEmpty()) {
                switch (model) {
                    case "email-login":
                    case "email-passwd":
                    case "email-register":
                        result = sendCode(template, params, email);
                        break;
                    case "email-remind":
                        result = sendRemindMsg(template, params, email);
                        break;
                }
            }
        }
        return result;
    }

    private void saveMessage(SysUser user, Map<String, Object> variables, String content) {

        SysMessage message = new SysMessage();

        message.setEsTitle("挪车提醒");
        message.setEsType("3");
        message.setEsReceiver(user.getPhone());
        message.setEsParam(JSONObject.toJSONString(variables));
        message.setEsContent(content);
        message.setEsSendTime(new Date());
        message.setEsSendStatus(SendMsgStatusEnum.SUCCESS.getCode());
        message.setEsSendNum(1);
        message.setCreateBy("admin");
        message.setCreateTime(new Date());
        message.setUpdateBy("admin");
        message.setUpdateTime(new Date());

        messageService.save(message);
    }

    /**
     * 发送通知
     *
     * @author zwf
     * @date created in 2025/5/17 13:03
     * @param: template
     * @param: params
     * @param: email
     * @return: boolean
     */
    private boolean sendRemindMsg(SysMessageTemplate template, JSONObject params, String email) {

        try {
            if (template != null && template.getTemplateContent() != null) {

                String userId = params.getString("user");
                String address = params.getString("address");

                if (userId != null && !userId.isEmpty()) {
                    SysUser user = userService.getById(userId);
                    AppUserSetting userSetting = userSettingService.getByUserId(userId);
                    // 准备模板变量
                    Map<String, Object> variables = new HashMap<>();

                    QueryWrapper<SysFiles> query = new QueryWrapper<>();
                    query.eq("create_by", userId);
                    query.eq("del_flag", "0");

                    SysFiles file = filesService.getOne(query);

                    if (file != null) {
                        variables.put("qrCodeUrl", file.getUrl());
                    }else{
                        variables.put("qrCodeUrl", "https://img.zwfcyy.top/echo/qrcode/default-wx.png");
                    }

                    variables.put("username", user.getRealname());
                    variables.put("licensePlate", userSetting.getPlateNumber());
                    variables.put("alertTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    variables.put("location", address);
                    variables.put("currentYear", Year.now().getValue());
                    // 渲染模板
                    template.setTemplateContent(TemplateUtil.renderFromDb(template.getTemplateContent(), variables));

                    EmailSendMsgHandle emailSendMsg = new EmailSendMsgHandle();

                    emailSendMsg.sendMsg(user.getEmail(), template.getTemplateName(), template.getTemplateContent());

                    saveMessage(user, variables, template.getTemplateContent());
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送验证码
     *
     * @author zwf
     * @date created in 2025/5/17 13:03
     * @param: template
     * @param: params
     * @param: email
     * @return: boolean
     */
    private boolean sendCode(SysMessageTemplate template, JSONObject params, String email) {
        try {
            if (template != null && template.getTemplateContent() != null) {

                String code = params.getString("code");

                SysUser user = userService.getUserByEmail(email);

                if (user == null){
                    user = new  SysUser();
                    user.setEmail(email);
                    user.setRealname(email);
                }

                // 准备模板变量
                Map<String, Object> variables = new HashMap<>();

                variables.put("username", user.getRealname());
                variables.put("verificationCode", code);
                variables.put("currentYear", Year.now().getValue());
                // 渲染模板
                template.setTemplateContent(TemplateUtil.renderFromDb(template.getTemplateContent(), variables));

                EmailSendMsgHandle emailSendMsg = new EmailSendMsgHandle();

                emailSendMsg.sendMsg(user.getEmail(), template.getTemplateName(), template.getTemplateContent());

                saveMessage(user, variables, template.getTemplateContent());

                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
}
